<template>
	<view class="publish-container" style="height:80%;overflow: scroll;">
		<!-- 顶部提示条 -->
		<view class="top-tip">禁止发布重复信息，私发广告营销类，含二维码内容等</view>

		<!-- 输入区域 -->
		<view class="input-wrap">
			<textarea class="content-textarea" placeholder="你想说点什么..." v-model="message" @input="handleInput"
				maxlength="1000"></textarea>
			<view class="word-count">{{ message.length }}/1000</view>
		</view>

		<view>
			<view style="display: flex; flex-wrap: wrap; justify-content: start; align-items: center;">
				<!-- 已上传图片预览区域 -->
				<view v-for="(imageUrl, index) in uploadedImages" :key="index" class="uploaded-image-item">
					<image :src="imageUrl" class="uploaded-image-preview" mode="aspectFill"></image>
					<view class="delete-uploaded-icon" @click="removeUploadedImage(index)">
						<image src="https://paole.hebeixiaoyu.cn/run/profile/upload/x.png" class="close-icon"></image>
					</view>
				</view>

				<view v-for="(image, index) in selectedImages" :key="index" class="image-item"
					style="margin:10rpx;width:30%">
					<image :src="image" class="uploaded-image" mode="aspectFill"></image>
					<view class="delete-icon" @click="removeImage(index)">
						<image src="https://paole.hebeixiaoyu.cn/run/profile/upload/x.png" class="close-icon"></image>
					</view>
				</view>
			</view>
			<!-- <view class="upload-container">
				<van-field clearable label="头像" center use-button-slot :border="false">
					<view slot="button">
						<van-uploader :file-list="fileList" @after-read="afterRead">
							<view class="text-center pl-[30rpx] bg-[#fff]">
								<van-image radius="20rpx" fit="cover" width="100rpx" height="100rpx" :src="headImg" />
								<van-icon name="arrow" size="16" class="ml--20rpx-" />
							</view>
						</van-uploader>
					</view>
				</van-field>
			</view> -->

			<view style="display: flex; justify-content: start; align-items: center;">
				<!-- 图片上传区域 -->
				<view class="image-upload-section">
					<view class="image-list">
						<view v-if="selectedImages.length < maxImageCount" class="camera-placeholder"
							@click="chooseImage">
							<image class="camera-icon"
								src="https://paole.hebeixiaoyu.cn/run/profile/upload/loukongxiangji.png"
								mode="widthFix"></image>
							<text class="upload-tip">{{maxImageCount - selectedImages.length}}张可上传</text>
						</view>
					</view>
				</view>

				<!-- 规则说明 -->
				<view class="rule-section">
					<text class="rule-item">1.普通消息可以免费发布</text>
					<text class="rule-item">2.商业推广联系<text class="admin-text"
							@click="showAdminContact">管理员</text>审核</text>
					<text class="rule-item">3.招聘/商业推广私发会被禁言、拉黑</text>
					<text class="rule-item">4.发布置顶帖子需联系<text class="admin-text"
							@click="showAdminContact">管理员</text>置顶</text>
				</view>
			</view>
		</view>

		<!-- 主题分类 -->
		<view class="category-row" @click="openCategoryPopup">
			<view class="category-title">
				<image class="category-icon" src="https://paole.hebeixiaoyu.cn/run/profile/upload/zhutifenlei.png"
					mode="widthFix"></image>
				<text class="title-text">主题分类</text>
			</view>
			<view class="category-value">
				<text>{{ currentCategoryName }}</text>
				<image class="arrow-icon" src="/static/image/arrow-right.png" mode="widthFix"></image>
			</view>
		</view>

		<!-- 是否匿名选项 -->
		<view class="category-row">
			<view class="category-title">
				<image class="category-icon" src="https://paole.hebeixiaoyu.cn/run/profile/upload/niming.png"
					mode="widthFix">
				</image>
				<text class="title-text">是否使用第二身份</text>
				<image class="arrow-icon" src="/static/image/arrow-right.png" mode="widthFix"></image>
			</view>
			<view class="category-value">
				<switch :checked="isAnonymous" @change="toggleAnonymous" />
			</view>
		</view>

		<!-- 是否禁止评论选项 -->
		<view class="category-row">
			<view class="category-title">
				<image class="category-icon" src="/static/image/jinzhipinglun.png" mode="widthFix"></image>
				<text class="title-text">禁止评论</text>
				<image class="arrow-icon" src="/static/image/arrow-right.png" mode="widthFix"></image>
			</view>
			<view class="category-value">
				<switch :checked="isCommentDisabled" @change="toggleCommentDisabled" />
			</view>
		</view>

		<!-- 发布规范弹窗 -->
		<view class="custom-popup" v-if="publishRuleShow">
			<view class="popup-mask" @click="closePublishRule"></view>
			<view class="popup-content">
				<view class="popup-header">
					<view class="popup-title">发布规范</view>
					<view class="close-btn" @click="closePublishRule">✕</view>
				</view>
				<view class="popup-text">
					<text>1.普通消息可以免费发布</text>
					<text>2.商业推广联系管理员（电话：13800138000）审核</text>
					<text>3.招聘/商业推广私发会被禁言、拉黑</text>
					<text>4.发布置顶帖子需联系管理员（电话：13800138000）置顶</text>
				</view>
			</view>
		</view>

		<!-- 主题分类选择弹窗 -->
		<view class="custom-popup" v-if="categoryPopupShow">
			<view class="popup-mask" @click="closeCategoryPopup"></view>
			<view class="popup-content category-popup-content">
				<view class="popup-header">
					<view class="popup-title">选择主题分类</view>
					<view class="close-btn" @click="closeCategoryPopup">✕</view>
				</view>
				<view class="category-list">
					<view v-for="(item, index) in categories" :key="item.id" class="category-item"
						:class="{ active: currentCategoryId === item.id }" @click="handleCategorySelect(item)">
						{{ item.fenleiName }}
					</view>
				</view>
			</view>
		</view>

		<!-- 底部规范说明和发布按钮 -->
		<view class="publish-section">
			<view class="rule-tip">
				*请自觉遵守<text class="rule-link" @click="showPublishRule">《发布规范》</text>，如有违规会被删帖、禁言、关小黑屋
			</view>
			<view class="publish-btn-wrap">
				<button class="publish-btn" @click="handlePublish">发布</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive
	} from 'vue';
	import {
		getCategories,
		publishPost,
		getSchoolMengerPhone
	} from '@/api/xiaoquan.js';
	import uploadRequest from '@/utils/uploadRequest.js';
	// 新增：存储所有上传成功的图片路径
	const uploadedImages = ref([]);
	const headImg = ref('https://aw2025ht.kangye.xyz/api/profile/upload/tou.jpg');
	const fileList = ref([]);
	const loading = ref(false);

	// 图片上传处理
	const afterRead = async (res) => {
		loading.value = true;
		try {
			await uploadRequest({
				filePath: res.detail.file.tempFilePath,
				url: '/api/front/hitch/passengerManager/uploadAvatar',
				formData: {
					multipart: res.detail.file
				},
				header: {
					"Authori-zation": uni.getStorageSync('token'),
					"Content-Type": "multipart/form-data"
				},
			}).then(result => {
				if (result.code == 200) {
					headImg.value = result.data;
					uploadedImages.value.push(result.data);
					uni.showToast({
						title: '图片上传成功',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: result.message || '上传失败',
						icon: 'none'
					});
				}
			});
		} catch (error) {
			console.log(error);
			uni.showToast({
				title: '上传出错，请重试',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	}
	// 响应式数据 
	const message = ref('');
	const categories = ref([]);
	const currentCategoryId = ref('');
	const currentCategoryName = ref('请选择分类');
	const publishRuleShow = ref(false);
	const categoryPopupShow = ref(true); // 默认显示主题分类弹窗
	const selectedImages = ref([]);
	const maxImageCount = 9;
	const adminPhone = '13800138000'; // 管理员电话
	const isAnonymous = ref(false); // 是否匿名
	const isCommentDisabled = ref(false); // 是否禁止评论
	const uploadProgress = ref(0); // 上传进度
	const isSubmitting = ref(false); // 提交状态
	const imageUrlString = ref(''); // 存储逗号分隔的图片URL字符串

	// 构造发布数据对象
	const postData = reactive({
		content: '',
		categoryId: '',
		categoryName: '',
		images: '', // 改为字符串类型
		isAnonymous: false,
		isCommentDisabled: false, // 新增是否禁止评论属性
		schoolId: uni.getStorageSync('school_id') || '5', // 假设学校ID
		createTime: new Date().toISOString()
	});

	// 获取分类数据
	const fetchCategories = async () => {
		try {
			const response = await getCategories();
			categories.value = response.data || [];
		} catch (error) {
			console.error('获取分类数据失败:', error);
			uni.showToast({
				title: '获取分类数据失败',
				icon: 'none'
			});
		}
	};

	// 输入事件
	const handleInput = () => {
		postData.content = message.value;
	};

	// 选择图片
	const chooseImage = async () => {
		const remaining = maxImageCount - selectedImages.value.length;
		if (remaining <= 0) {
			uni.showToast({
				title: '最多只能上传9张图片',
				icon: 'none'
			});
			return;
		}

		try {
			const res = await uni.chooseImage({
				count: remaining,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera']
			});
			// 遍历选择的图片路径，直接调用上传单张图片函数
			for (let i = 0; i < res.tempFilePaths.length; i++) {
				await uploadRequest({
					filePath: res.tempFilePaths[i],
					url: '/api/front/hitch/passengerManager/uploadAvatar',
					formData: {
						file: res.tempFilePaths[i] // 修正为file参数
					},
					header: {
						"Authori-zation": uni.getStorageSync('token'),
						"Content-Type": "multipart/form-data"
					},
				}).then(result => {
					if (result.code == 200) {
						headImg.value = result.data;
						uploadedImages.value.push(result.data); // 添加到上传成功数组
						uni.showToast({
							title: '图片上传成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: result.message || '上传失败',
							icon: 'none'
						});
					}
				});
			}
			uni.showToast({
				title: '图片上传完成',
				icon: 'success'
			});
		} catch (err) {
			console.error('选择图片失败:', err);
		}
	};

	// 删除本地选中的图片
	const removeImage = (index) => {
		selectedImages.value.splice(index, 1);
		console.log('删除本地图片后:', selectedImages.value);
	};

	// 删除已上传的图片
	const removeUploadedImage = (index) => {
		uploadedImages.value.splice(index, 1);
		console.log('删除已上传图片后:', uploadedImages.value);
		uni.showToast({
			title: '已删除图片',
			icon: 'success'
		});
	};

	// 展示发布规范弹窗
	const showPublishRule = () => {
		publishRuleShow.value = true;
	};

	// 关闭发布规范弹窗
	const closePublishRule = () => {
		publishRuleShow.value = false;
	};

	// 打开分类选择弹窗
	const openCategoryPopup = () => {
		categoryPopupShow.value = true;
	};

	// 关闭分类选择弹窗
	const closeCategoryPopup = () => {
		categoryPopupShow.value = false;
	};

	// 选择分类
	const handleCategorySelect = (item) => {
		currentCategoryId.value = item.id;
		currentCategoryName.value = item.fenleiName;
		postData.categoryId = item.id;
		postData.categoryName = item.fenleiName;
		categoryPopupShow.value = false;
	};

	// 切换匿名状态
	const toggleAnonymous = (e) => {
		isAnonymous.value = e.detail.value;
		postData.isAnonymous = isAnonymous.value;
	};

	// 切换禁止评论状态
	const toggleCommentDisabled = (e) => {
		isCommentDisabled.value = e.detail.value;
		postData.isCommentDisabled = isCommentDisabled.value;
	};

	// 显示管理员联系方式
	const showAdminContact = () => {
		getSchoolMengerPhone().then((apiRes) => { // 将参数名改为 apiRes 避免冲突
			if (apiRes && apiRes.data) {
				uni.showModal({
					title: '墙墙の微信',
					content: apiRes.data, // 使用 apiRes 访问接口返回数据
					confirmText: '复制',
					cancelText: '取消',
					success: (modalRes) => { // 模态框回调参数改为 modalRes
						if (modalRes.confirm) {
							console.log('用户点击了确定');

							// 检查 apiRes.data 是否存在且为字符串
							if (typeof apiRes.data === 'string' && apiRes.data.trim() !== '') {
								uni.setClipboardData({
									data: apiRes.data,
									success: () => {
										uni.showToast({
											title: '微信已复制',
											icon: 'success'
										});
									},
									fail: (err) => {
										console.error('复制失败', err);
										uni.showToast({
											title: '复制失败，请稍后重试',
											icon: 'none'
										});
									}
								});
							} else {
								uni.showToast({
									title: '微信数据格式错误，无法复制',
									icon: 'none'
								});
							}
						}
					}
				});
			} else {
				uni.showToast({
					title: '获取客服微信失败',
					icon: 'none'
				});
			}
		}).catch((err) => {
			console.error('获取客服微信请求失败', err);
			uni.showToast({
				title: '网络请求失败，请稍后重试',
				icon: 'none'
			});
		});
	};

	// 上传单张图片
	const uploadSingleImage = async (imagePath) => {
		try {
			const response = await uploadRequest({
				url: "/api/front/hitch/passengerManager/upload",
				filePath: imagePath,
				formData: {
					schoolId: postData.schoolId,
					type: "post_image",
					file: imagePath // 修正为file参数
				}
			});

			if (response.code === 200 && response.data && response.data.url) {
				uploadedImages.value.push(response.data.url); // 添加到上传成功数组
				return response.data.url;
			} else {
				throw new Error(response.message || "图片上传失败");
			}
		} catch (error) {
			console.error("单张图片上传失败:", error);
			throw error;
		}
	};

	// 上传所有图片并生成逗号分隔字符串
	const uploadAllImages = async (images) => {
		if (!images || images.length === 0) {
			return '';
		}

		const uploadedUrls = [];
		const totalImages = images.length;
		let errorCount = 0; // 记录上传失败的图片数量

		for (let i = 0; i < totalImages; i++) {
			const image = images[i];
			try {
				// 显示上传进度
				uploadProgress.value = ((i + 1) / totalImages) * 100;
				uni.showLoading({
					title: `上传图片 ${i+1}/${totalImages}`,
					mask: true
				});

				const url = await uploadSingleImage(image);
				uploadedUrls.push(url);
			} catch (error) {
				errorCount++;
				console.error(`图片${i+1}上传失败:`, error);
				uni.showToast({
					title: `图片${i+1}上传失败，已跳过`,
					icon: 'none',
					duration: 2000
				});
			} finally {
				uni.hideLoading();
			}
		}

		// 提示上传结果
		if (errorCount > 0) {
			uni.showToast({
				title: `成功上传${totalImages - errorCount}张，${errorCount}张失败`,
				icon: 'none',
				duration: 3000
			});
		}

		return uploadedUrls.join(',');
	};

	// 发布逻辑
	const handlePublish = async () => {
		uni.showModal({
			title: '【重要提示】',
			content: `发布内容需遵守法律法规，严禁传播违法、诽谤、色情、广告等不当信息。
如发布不当言论，您将自行承担相应法律责任。确定继续发布？`,
			confirmText: '确定',
			cancelText: '取消',
			success: (res) => {
				if (res.confirm) {
					fabu();
				} else if (res.cancel) {
					return;
				}
			}
		});

	};


	const fabu = async () => {
		// 表单验证
		if (!message.value.trim()) {
			uni.showToast({
				title: '请输入内容',
				icon: 'none'
			});
			return;
		}
		if (!currentCategoryId.value) {
			uni.showToast({
				title: '请选择主题分类',
				icon: 'none'
			});
			return;
		}
		if (isSubmitting.value) return;

		isSubmitting.value = true;
		uni.showLoading({
			title: '发布中...',
			mask: true
		});

		try {
			// // 上传所有图片并获取逗号分隔的URL字符串
			// if (selectedImages.value.length > 0) {
			// 	uni.showToast({
			// 		title: '正在上传图片...',
			// 		icon: 'loading'
			// 	});
			// 	postData.images = await uploadAllImages(selectedImages.value);
			// }

			postData.images = uploadedImages.value.join(',');
			// 构造发布数据
			const publishData = {
				...postData,
				content: message.value
			};
			publishData.isCommentDisabled = publishData.isCommentDisabled ? 1 : 0
			console.log('最终发布数据:', publishData);

			// 调用发布API
			const response = await publishPost(publishData);

			console.log('发布API响应:', response);

			if (response && response.code === 200) {
				uni.showToast({
					title: '发布成功',
					icon: 'success',
					duration: 2000
				});
				// 发布成功后清空上传数组
				uploadedImages.value = [];
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			} else {
				const errorMsg = response && response.message ?
					`发布失败: ${response.message}` :
					'发布失败，请稍后重试';
				throw new Error(errorMsg);
			}
		} catch (error) {
			console.error('发布过程中发生错误:', error);
			uni.showToast({
				title: error.message || '发布失败，请稍后重试',
				icon: 'none',
				duration: 3000
			});
		} finally {
			uni.hideLoading();
			isSubmitting.value = false;
		}
	}


	// 页面加载时获取分类
	onMounted(() => {
		fetchCategories();
	});
</script>

<style scoped>
	/* 样式部分保持不变，新增图标样式 */
	.publish-container {
		padding: 20rpx;
		background-color: #fff;
		min-height: 100vh;
		padding-bottom: 100rpx;
	}

	/* 顶部提示条 */
	.top-tip {
		font-size: 26rpx;
		color: #888;
		background-color: #fef5e9;
		padding: 20rpx;
		border-radius: 8rpx;
		margin-bottom: 25rpx;
		border-left: 5rpx solid #f5a623;
	}

	/* 输入区域 */
	.input-wrap {
		margin-bottom: 35rpx;
		position: relative;
		border-bottom: 1rpx solid #f2f2f2;
		padding-bottom: 25rpx;
	}

	.content-textarea {
		width: 100%;
		min-height: 220rpx;
		border: none;
		padding: 0;
		font-size: 32rpx;
		box-sizing: border-box;
		resize: none;
		line-height: 1.6;
	}

	.content-textarea::placeholder {
		color: #bbb;
	}

	.word-count {
		text-align: right;
		font-size: 26rpx;
		color: #999;
		margin-top: 15rpx;
		padding-right: 10rpx;
	}

	/* 图片上传区域 */
	.image-upload-section {
		margin: 15rpx;
	}

	.image-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.image-item,
	.uploaded-image-item {
		width: 200rpx;
		height: 200rpx;
		position: relative;
		border-radius: 10rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
		margin: 10rpx;
		width: 30%;
	}

	.uploaded-image,
	.uploaded-image-preview {
		width: 100%;
		height: 100%;
	}

	.delete-icon,
	.delete-uploaded-icon {
		position: absolute;
		top: 5rpx;
		right: 5rpx;
		width: 42rpx;
		height: 42rpx;
		background: rgba(0, 0, 0, 0.6);
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.close-icon {
		width: 24rpx;
		height: 24rpx;
	}

	.camera-placeholder {
		width: 200rpx;
		height: 200rpx;
		border: 1px dashed #c8c8c8;
		border-radius: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #fafafa;
		position: relative;
	}

	.camera-icon {
		width: 70rpx;
		height: 70rpx;
	}

	/* 新增的上传提示样式 */
	.upload-tip {
		position: absolute;
		bottom: 10rpx;
		left: 0;
		right: 0;
		text-align: center;
		font-size: 24rpx;
		color: #999;
		background-color: rgba(0, 0, 0, 0.5);
		padding: 5rpx 0;
		border-radius: 4rpx;
		color: white;
	}

	/* 规则说明 */
	.rule-section {
		padding: 20rpx 0 30rpx;
		flex: 1;
		margin-left: 20rpx;
	}

	.rule-item {
		display: block;
		font-size: 28rpx;
		color: #e64340;
		line-height: 1.8;
		padding: 8rpx 0;
	}

	.admin-text {
		color: #007AFF;
		text-decoration: underline;
		padding: 0 8rpx;
	}

	/* 主题分类 */
	.category-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f2f2f2;
	}

	.category-title {
		display: flex;
		align-items: center;
	}

	.category-icon {
		width: 55rpx;
		height: 55rpx;
		margin-right: 10rpx;
	}

	/* 新增的评论图标，假设你有一个comment.png图标 */
	.category-icon[src$="comment.png"] {
		width: 50rpx;
		height: 50rpx;
	}

	.title-text {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
	}

	.category-value {
		display: flex;
		align-items: center;
		color: #666;
		font-size: 30rpx;
	}

	.arrow-icon {
		width: 30rpx;
		height: 30rpx;
		margin-left: 15rpx;
	}

	/* 弹窗样式 */
	.custom-popup {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		top: 0;
		z-index: 999;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.popup-mask {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.4);
	}

	.popup-content {
		position: relative;
		width: 85%;
		background-color: #fff;
		border-radius: 25rpx;
		overflow: hidden;
		z-index: 1000;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 35rpx;
		background-color: #f8f8f8;
		border-bottom: 1rpx solid #eee;
	}

	.popup-title {
		font-size: 36rpx;
		font-weight: bold;
	}

	.close-btn {
		font-size: 40rpx;
		color: #999;
		padding: 10rpx 20rpx;
	}

	.popup-text {
		padding: 40rpx 35rpx;
		font-size: 30rpx;
		line-height: 1.8;
		color: #333;
	}

	.popup-text text {
		display: block;
		margin-bottom: 25rpx;
	}

	/* 分类选择弹窗 */
	.category-popup-content {
		max-height: 75vh;
	}

	.category-list {
		padding: 25rpx;
	}

	.category-item {
		padding: 30rpx;
		font-size: 30rpx;
		border-bottom: 1rpx solid #f2f2f2;
		text-align: center;
	}

	.category-item:last-child {
		border-bottom: none;
	}

	.category-item.active {
		color: #007AFF;
		background-color: #f0f7ff;
		font-weight: 500;
	}

	/* 发布区域 - 非固定定位 */
	.publish-section {
		margin-top: 60rpx;
	}

	.rule-tip {
		font-size: 26rpx;
		color: #999;
		text-align: center;
		padding: 20rpx 0;
	}

	.rule-link {
		color: #007AFF;
		padding: 0 8rpx;
	}

	/* 发布按钮 */
	.publish-btn-wrap {
		padding: 10rpx 0;
	}

	.publish-btn {
		width: 100%;
		background: #007AFF;
		color: #fff;
		font-size: 36rpx;
		text-align: center;
		border: none;
		box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
	}
</style>